<template>
  <div class="map-container">
    <div id="map-chart" ref="mapChart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'EChartsMap',
  props: {
    activeRegion: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      chart: null,
      currentProvince: null,
      mapLoaded: false,
      touchStartTime: 0,
      touchStartPos: null,
      isTouchMoved: false,
      isMobile: false,
      touchTimer: null
    }
  },
  watch: {
    activeRegion(newVal, oldVal) {
      console.log('[Map] activeRegion changed:', oldVal, '->', newVal)
      if (this.chart && this.mapLoaded) {
        if (newVal === null || newVal === '') {
          // 取消选中
          if (this.currentProvince) {
            this.chart.dispatchAction({
              type: 'unselect',
              seriesIndex: 0,
              name: this.currentProvince
            })
            this.currentProvince = null
          }
        } else if (newVal !== oldVal) {
          // 根据简化名称找到完整省份名称
          const provinceMap = {
            '北京': '北京市',
            '天津': '天津市',
            '上海': '上海市',
            '重庆': '重庆市',
            '内蒙古': '内蒙古自治区',
            '广西': '广西壮族自治区',
            '西藏': '西藏自治区',
            '宁夏': '宁夏回族自治区',
            '新疆': '新疆维吾尔自治区',
            '香港': '香港特别行政区',
            '澳门': '澳门特别行政区',
            '台湾': '台湾省'
          }
          
          const fullProvinceName = provinceMap[newVal] || newVal + '省'
          
          // 先取消当前选中
          if (this.currentProvince) {
            this.chart.dispatchAction({
              type: 'unselect',
              seriesIndex: 0,
              name: this.currentProvince
            })
          }
          
          // 再选中新省份
          this.currentProvince = fullProvinceName
          this.chart.dispatchAction({
            type: 'select',
            seriesIndex: 0,
            name: fullProvinceName
          })
        }
      }
    }
  },
  mounted() {
    // 检测是否为移动设备或移动端视图
    this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768
    
    this.$nextTick(() => {
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    // 清理事件监听和实例
    window.removeEventListener('resize', this.handleResize)
    const chartDom = this.$refs.mapChart
    if (chartDom) {
      chartDom.removeEventListener('touchstart', this.handleTouchStart)
      chartDom.removeEventListener('touchmove', this.handleTouchMove)
      chartDom.removeEventListener('touchend', this.handleTouchEnd)
    }
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    async initChart() {
      const chartDom = this.$refs.mapChart
      if (!chartDom) {
        console.error('[Map] Chart container not found')
            return
          }

      // 初始化 ECharts 实例
      this.chart = echarts.init(chartDom, null, {
        renderer: 'canvas',
        useDirtyRect: false,
        devicePixelRatio: window.devicePixelRatio
      })

      try {
        const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
        if (!response.ok) {
          throw new Error('Failed to load map data')
        }
        const mapData = await response.json()
        
        echarts.registerMap('china', mapData)
        this.mapLoaded = true
        
        // 创建简化省份名称的映射函数
        const simplifyProvinceName = (param) => {
          // 处理不同参数类型
          let name = '';
          
          // 如果是对象(ECharts格式化函数的参数)
          if (typeof param === 'object' && param !== null) {
            name = param.name || '';
          } 
          // 如果是字符串(直接传入的省份名)
          else if (typeof param === 'string') {
            name = param;
          }
          // 其他情况
          else {
            return '';
          }
          
          const specialNames = {
            '内蒙古自治区': '内蒙古',
            '广西壮族自治区': '广西',
            '西藏自治区': '西藏',
            '宁夏回族自治区': '宁夏',
            '新疆维吾尔自治区': '新疆',
            '香港特别行政区': '香港',
            '澳门特别行政区': '澳门',
            '北京市': '北京',
            '天津市': '天津',
            '上海市': '上海',
            '重庆市': '重庆'
          }
          
          return specialNames[name] || (name ? name.replace(/(省|市|自治区|特别行政区)$/, '') : '');
        }
        
        // 根据设备类型调整配置
        const baseZoom = this.isMobile ? 1.8 : 0.8
            const option = {
          backgroundColor: '#87CEEB', // 修改为天蓝色
              geo: {
            show: true,
            map: 'china',
            roam: true,
            zoom: baseZoom,
            center: [104.5, 36.5],
            layoutSize: '90%',
            layoutCenter: ['50%', '50%'],
                scaleLimit: {
              min: this.isMobile ? 0.8 : 0.5,
              max: this.isMobile ? 8 : 5
            },
                itemStyle: {
              areaColor: '#6ba8e5',
              borderColor: '#183a72',
              borderWidth: 1,
              shadowColor: 'rgba(0,0,0,0)',
              shadowBlur: 0,
              shadowOffsetY: 0
            },
            label: {
              show: true,
              color: '#fff',
              fontSize: this.isMobile ? 14 : 12,
              formatter: simplifyProvinceName // 使用简化省份名称函数
                },
                emphasis: {
                  label: {
                show: true,
                color: '#fff',
                fontSize: this.isMobile ? 16 : 14,
                fontWeight: '500',
                textShadowColor: 'rgba(0,0,0,0)',
                textShadowBlur: 0
              },
              itemStyle: {
                areaColor: '#23408e',
                borderColor: '#183a72',
                borderWidth: 1.2,
                shadowColor: 'rgba(0,0,0,0)',
                shadowBlur: 0,
                shadowOffsetY: 0
              }
            },
            select: {
              label: {
                show: true,
                color: '#fff',
                fontSize: this.isMobile ? 16 : 14,
                fontWeight: '600',
                textShadowColor: 'rgba(0,0,0,0)',
                textShadowBlur: 0
                  },
                  itemStyle: {
                areaColor: '#23408e',
                borderColor: '#183a72',
                borderWidth: 2,
                shadowColor: 'rgba(0,0,0,0)',
                shadowBlur: 0,
                shadowOffsetY: 0
              }
                  }
                },
          series: [{
            type: 'map',
            map: 'china',
            geoIndex: 0,
            roam: true,
            zoom: baseZoom,
            center: [104.5, 36.5],
            selectedMode: 'single',
                label: {
              show: true,
              color: '#fff',
              fontSize: this.isMobile ? 14 : 12,
              formatter: simplifyProvinceName // 使用简化函数
            },
            itemStyle: {
              areaColor: '#6ba8e5',
              borderColor: '#183a72',
              borderWidth: 1,
              shadowColor: 'rgba(0,0,0,0)',
              shadowBlur: 0,
              shadowOffsetY: 0
            },
            emphasis: {
              label: {
                show: true,
                color: '#fff',
                fontSize: this.isMobile ? 16 : 14,
                fontWeight: '500',
                textShadowColor: 'rgba(0,0,0,0)',
                textShadowBlur: 0
              },
              itemStyle: {
                areaColor: '#23408e',
                borderColor: '#183a72',
                borderWidth: 1.2,
                shadowColor: 'rgba(0,0,0,0)',
                shadowBlur: 0,
                shadowOffsetY: 0
              }
            },
            select: {
              label: {
                show: true,
                color: '#fff',
                fontSize: this.isMobile ? 16 : 14,
                fontWeight: '600',
                textShadowColor: 'rgba(0,0,0,0)',
                textShadowBlur: 0
              },
              itemStyle: {
                areaColor: '#23408e',
                borderColor: '#183a72',
                borderWidth: 2,
                shadowColor: 'rgba(0,0,0,0)',
                shadowBlur: 0,
                shadowOffsetY: 0
                }
              }
          }]
        }

        this.chart.setOption(option)
        this.bindEvents()
      } catch (error) {
        console.error('[Map] Failed to initialize chart:', error)
        this.chart.setOption({
          title: {
            text: '地图加载失败，请刷新重试',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#fff',
              fontSize: 16
            }
          }
        })
      }
    },

    handleTouchStart(e) {
      if (!this.chart) return
      
      e.preventDefault()
      const touch = e.touches[0]
      const rect = this.$refs.mapChart.getBoundingClientRect()
      
      // 计算相对于图表容器的坐标
      const x = touch.clientX - rect.left
      const y = touch.clientY - rect.top
      
      console.log('[Map] Touch Start:', {
        x,
        y,
        clientX: touch.clientX,
        clientY: touch.clientY,
        rect: {
          left: rect.left,
          top: rect.top,
          width: rect.width,
          height: rect.height
        },
        time: Date.now()
            })
      
      this.touchStartPos = {
        x,
        y,
        time: Date.now()
      }
      this.isTouchMoved = false

      // 添加点击延迟处理
      this.touchTimer = setTimeout(() => {
        if (!this.isTouchMoved) {
          console.log('[Map] Long press detected')
          this.handleMapPress(this.touchStartPos)
        }
      }, 200)
        },

    handleTouchMove(e) {
      if (!this.chart || !this.touchStartPos) return
      
      e.preventDefault()
      const touch = e.touches[0]
      const rect = this.$refs.mapChart.getBoundingClientRect()
      
      // 计算相对移动距离
      const currentX = touch.clientX - rect.left
      const currentY = touch.clientY - rect.top
      const deltaX = currentX - this.touchStartPos.x
      const deltaY = currentY - this.touchStartPos.y
      
      // 调整移动阈值和灵敏度
      if (Math.abs(deltaX) > 3 || Math.abs(deltaY) > 3) {
        if (!this.isTouchMoved) {
          console.log('[Map] Touch Move Started:', { deltaX, deltaY })
          clearTimeout(this.touchTimer)
        }
        this.isTouchMoved = true

        // 获取当前视图
        const view = this.chart.getModel().getComponent('geo').coordinateSystem
        const center = view.getCenter()
        const zoom = view.getZoom()
        
        // 计算新的中心点
        // 根据缩放级别调整移动速度
        const moveSpeed = 1 / (zoom * 2)
        // 方向调整：增加deltaX，使得左右移动方向更为一致
        let newCenter = [
          center[0] - deltaX * moveSpeed,
          center[1] + deltaY * moveSpeed
        ]

        // 限制中心点范围，放宽限制，防止地图拖出可视区域但允许足够的拖动范围
        // 将经度范围调整得更宽松
        newCenter[0] = Math.max(70, Math.min(140, newCenter[0]))
        newCenter[1] = Math.max(15, Math.min(55, newCenter[1]))

        // 应用新的视图位置
        this.chart.setOption({
            geo: {
            center: newCenter,
            animationDurationUpdate: 0
          },
          series: [{
            center: newCenter,
            animationDurationUpdate: 0
          }]
        })

        // 更新起始位置
        this.touchStartPos = {
          x: currentX,
          y: currentY,
          time: Date.now()
        }
      }
    },

    handleTouchEnd(e) {
      if (!this.chart) return
      
      e.preventDefault()
      clearTimeout(this.touchTimer)
      
      const duration = this.touchStartPos ? Date.now() - this.touchStartPos.time : 0
      console.log('[Map] Touch End:', {
        moved: this.isTouchMoved,
        duration: duration
      })
      
      // 处理快速点击
      if (this.touchStartPos && duration < 200 && !this.isTouchMoved) {
        console.log('[Map] Quick tap detected')
        this.handleMapPress(this.touchStartPos)
      }

      // 恢复动画
      if (this.isTouchMoved) {
        this.chart.setOption({
          geo: {
            animationDurationUpdate: 300,
            animationEasingUpdate: 'cubicOut'
          },
          series: [{
            animationDurationUpdate: 300,
            animationEasingUpdate: 'cubicOut'
          }]
        })
      }

      this.touchStartPos = null
      this.isTouchMoved = false
    },

    // 优化区域查找方法
    findRegionByPoint(point) {
      if (!point) {
        console.log('[Map] Invalid point for region search')
        return null
      }
      
      console.log('[Map] Searching region for point:', point)
      
      try {
        // 直接使用ECharts内置API获取点击位置的区域
        const result = this.chart.getZr().handler.findHover(point[0], point[1])
        
        // 如果找到交互元素，获取相关的数据
        if (result && result.target) {
          // 尝试获取省份名称
          const dataIndex = result.target.dataIndex
          if (typeof dataIndex === 'number') {
            const model = this.chart.getModel()
            const mapSeries = model.getSeriesByIndex(0)
            if (mapSeries) {
              const data = mapSeries.getData()
              const name = data.getName(dataIndex)
              if (name) {
                console.log('[Map] Found exact region:', name)
                return {
                  name: name,
                  dataIndex: dataIndex
                }
              }
            }
          }
        }
        
        // 回退到使用坐标转换方法
        const seriesModel = this.chart.getModel().getSeriesByIndex(0)
        if (!seriesModel) return null
        
        const coordSys = seriesModel.coordinateSystem
        if (!coordSys) return null
        
        // 将屏幕坐标转换为地理坐标
        const geo = this.chart.convertFromPixel({ seriesIndex: 0 }, [point[0], point[1]])
        if (!geo) return null
        
        console.log('[Map] Converted geo coordinates:', geo)
        
        // 找出包含该地理坐标的省份
        for (let i = 0; i < coordSys.regions.length; i++) {
          const region = coordSys.regions[i]
          if (region.contain(geo)) {
            console.log('[Map] Found containing region:', region.name)
            return {
              name: region.name,
              region: region
            }
          }
        }
        
        // 如果没有找到，使用最近距离的省份
        let nearestRegion = null
        let minDistance = Infinity
        
        for (let i = 0; i < coordSys.regions.length; i++) {
          const region = coordSys.regions[i]
          const center = region.center
          if (!center) continue
          
          // 计算点到中心的距离
          const distance = Math.sqrt(
            Math.pow(geo[0] - center[0], 2) + 
            Math.pow(geo[1] - center[1], 2)
          )
          
          if (distance < minDistance) {
            minDistance = distance
            nearestRegion = region
          }
        }
        
        if (nearestRegion) {
          console.log('[Map] Found nearest region:', nearestRegion.name, 'distance:', minDistance)
          return {
            name: nearestRegion.name,
            region: nearestRegion
          }
        }
      } catch (error) {
        console.error('[Map] Error in findRegionByPoint:', error)
      }
      
      console.log('[Map] No region found for point')
      return null
    },

    // 处理地图按压
    handleMapPress(pos) {
      if (!pos) {
        console.log('[Map] Invalid press position')
        return
      }
      
      console.log('[Map] Processing map press at:', {
        x: pos.x,
        y: pos.y,
        isMobile: this.isMobile
      })
      
      try {
        // 直接使用屏幕坐标查找区域
        const result = this.findRegionByPoint([pos.x, pos.y])
        if (result) {
          console.log('[Map] Found region on press:', result.name)
          this.handleProvinceClick(result.name)
        } else {
          console.log('[Map] Press detected on empty area')
        }
      } catch (error) {
        console.error('[Map] Error in handleMapPress:', error)
      }
    },

    // 处理省份点击
    handleProvinceClick(provinceName) {
      if (!provinceName) {
        console.log('[Map] Invalid province name')
        return
      }

      console.log('[Map] Province clicked:', {
        name: provinceName,
        currentProvince: this.currentProvince,
        isMobile: this.isMobile
      })

      try {
        if (this.currentProvince === provinceName) {
          // 取消选中
          console.log('[Map] Unselecting province:', provinceName)
          this.currentProvince = null
          this.chart.dispatchAction({
            type: 'unselect',
            seriesIndex: 0,
            name: provinceName
          })
          
          // 对外发出事件
          console.log('[Map] 发送null (取消选中)')
          this.$emit('region-click', null)
        } else {
          // 选中新省份
          console.log('[Map] Selecting new province:', provinceName)
          
          if (this.currentProvince) {
            this.chart.dispatchAction({
              type: 'unselect',
              seriesIndex: 0,
              name: this.currentProvince
            })
          }

          this.currentProvince = provinceName
          
          // 使用 nextTick 确保状态更新后再执行动画
          this.$nextTick(() => {
            // 选中新省份
            this.chart.dispatchAction({
              type: 'select',
              seriesIndex: 0,
              name: provinceName
            })
            
            // 对外发出事件，将省份名称简化
            const simplifiedName = this.simplifyProvinceName(provinceName)
            console.log('[Map] 发送简化省份名称:', simplifiedName, '原始省份名称:', provinceName)
            this.$emit('region-click', simplifiedName)
          })
        }
      } catch (error) {
        console.error('[Map] Error in handleProvinceClick:', error)
      }
    },

    bindEvents() {
      if (!this.chart) return
      
      console.log('[Map] Binding events, isMobile:', this.isMobile)

      // 移除之前的事件监听
      const chartDom = this.$refs.mapChart
      if (chartDom) {
        chartDom.removeEventListener('touchstart', this.handleTouchStart)
        chartDom.removeEventListener('touchmove', this.handleTouchMove)
        chartDom.removeEventListener('touchend', this.handleTouchEnd)
      }

      // 清除之前的点击事件
      this.chart.off('click')

      // 重新绑定事件
      if (this.isMobile) {
        console.log('[Map] Setting up mobile events')
        chartDom.addEventListener('touchstart', this.handleTouchStart, { passive: false })
        chartDom.addEventListener('touchmove', this.handleTouchMove, { passive: false })
        chartDom.addEventListener('touchend', this.handleTouchEnd, { passive: false })
      }
      
      // 统一的点击事件，移动端和PC端共用一个处理逻辑
      this.chart.on('click', (params) => {
        // 阻止默认事件，避免触发多次
        if (params && params.event) {
          params.event.event && params.event.event.preventDefault && params.event.event.preventDefault()
          params.event.preventDefault && params.event.preventDefault()
        }
        
        // 确保点击事件已完全处理后再执行查找
        this.$nextTick(() => {
          if (params && params.event) {
            const event = params.event.event || params.event
            // 获取点击的屏幕坐标
            const rect = chartDom.getBoundingClientRect()
            const clientX = event.clientX || (event.touches && event.touches[0] && event.touches[0].clientX)
            const clientY = event.clientY || (event.touches && event.touches[0] && event.touches[0].clientY)
            
            if (typeof clientX === 'number' && typeof clientY === 'number') {
              const point = [
                clientX - rect.left,
                clientY - rect.top
              ]
              
              console.log('[Map] Chart click at point:', point)
              
              // 使用坐标查找省份
              const result = this.findRegionByPoint(point)
              if (result && result.name) {
                // 直接发送省份简化后的名称 - 简化代码减少嵌套
                const provinceName = result.name
                const simplifiedName = this.simplifyProvinceName(provinceName)
                console.log('[Map] 发送简化省份名称:', simplifiedName, '原始省份名称:', provinceName)
                
                // 同步更新选中状态
                if (this.currentProvince) {
                  this.chart.dispatchAction({
                    type: 'unselect',
                    seriesIndex: 0,
                    name: this.currentProvince
                  })
                }
                
                if (this.currentProvince === provinceName) {
                  // 如果点击了当前选中的省份，取消选中
                  this.currentProvince = null
                  this.$emit('region-click', null)
                } else {
                  // 选中新省份
                  this.currentProvince = provinceName
                  this.chart.dispatchAction({
                    type: 'select',
                    seriesIndex: 0,
                    name: provinceName
                  })
                  
                  // 直接发送事件，避免嵌套过深
                  this.$emit('region-click', simplifiedName)
                  console.log('[Map] region-click事件已发送:', simplifiedName)
                }
              } else {
                console.log('[Map] 未找到省份，点击在空白区域')
              }
            }
          }
        })
      })

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        // 更新移动端状态
        const wasMobile = this.isMobile
        this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768
        
        // 如果设备类型改变，重新绑定事件
        if (wasMobile !== this.isMobile) {
          this.bindEvents()
        }
        
        // 调整图表大小
        this.handleResize()
      })
    },
    
    handleResize() {
      if (this.chart) {
        this.chart.resize()
        
        // 根据当前视图调整缩放
        const baseZoom = this.isMobile ? 1.8 : 0.8
        this.chart.setOption({
          geo: {
            zoom: baseZoom,
            scaleLimit: {
              min: this.isMobile ? 0.8 : 0.5,
              max: this.isMobile ? 8 : 5
            }
          },
          series: [{
            zoom: baseZoom
          }]
        })
      }
    },

    resetMap() {
      const baseZoom = this.isMobile ? 1.8 : 0.8
      this.chart.setOption({
        geo: {
          zoom: baseZoom,
          center: [104.5, 36.5],
          animationDuration: 800
        }
      })
    },

    simplifyProvinceName(name) {
      if (!name) return ''
      
      const specialNames = {
        '内蒙古自治区': '内蒙古',
        '广西壮族自治区': '广西',
        '西藏自治区': '西藏',
        '宁夏回族自治区': '宁夏',
        '新疆维吾尔自治区': '新疆',
        '香港特别行政区': '香港',
        '澳门特别行政区': '澳门',
        '北京市': '北京',
        '天津市': '天津',
        '上海市': '上海',
        '重庆市': '重庆'
      }
      
      const result = specialNames[name] || (name ? name.replace(/(省|市|自治区|特别行政区)$/, '') : '');
      console.log('[Map] 省份名称简化:', name, '->', result);
      return result;
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 50vh;
  background-color: #1A1C3D;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止溢出 */
}

.header {
  height: 60px;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #1A1C3D;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 10; /* 确保导航在地图上层 */
}

.title {
  color: #fff;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.reset-btn {
  width: 32px;
  height: 32px;
  padding: 6px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(41, 165, 255, 0.2);
}

.reset-btn:hover {
  background-color: rgba(41, 165, 255, 0.3);
}

.reset-btn:active {
  transform: scale(0.95);
  background-color: rgba(41, 165, 255, 0.4);
}

.reset-btn img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  filter: brightness(0) invert(1); /* 将图标变为白色 */
  opacity: 0.8;
}

#map-chart {
  flex: 1;
  width: 100%;
  min-height: 0;
  background-color: #1A1C3D;
  touch-action: none;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
  border-radius: 0;
  position: relative;
  overflow: hidden; /* 防止溢出 */
}

/* 添加移动端响应式样式 */
@media screen and (max-width: 768px) {
  .header {
    height: 50px;
    padding: 0 16px;
  }

  .title {
    font-size: 18px;
  }

  .reset-btn {
    width: 28px;
    height: 28px;
    border-radius: 6px;
  }

  #map-chart {
    touch-action: pinch-zoom;
    -webkit-overflow-scrolling: touch;
  }
}

/* 添加移动端点击反馈 */
#map-chart:active {
  cursor: grabbing !important;
}

.top-stats {
  display: flex;
  justify-content: space-around;
  padding: 15px;
  margin: 15px 15px 10px;
  background-color: #282C54;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  
  .top-stat-item {
    text-align: center;
    .top-stat-value {
      font-size: 28px;
      font-weight: bold;
      display: block;
      color: #29A5FF;
      margin-bottom: 5px;
    }
    .top-stat-label {
      font-size: 12px;
      color: #f0f0f0;
    }
  }
}
</style>
